<template>
  <div class="deal-detail">
    <!-- 添加面包屑导航 -->
    <div class="breadcrumb-nav">
      <el-breadcrumb>
        <el-breadcrumb-item :to="{ path: '/deals' }">{{ $t('限时秒杀') }}</el-breadcrumb-item>
        <el-breadcrumb-item>{{ $t('优惠券详情') }}</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <div class="product-content">
      <!-- 左侧商品图片区域 -->
      <div class="product-gallery">
        <div class="main-image">
          <el-image :src="deal?.image" :alt="deal?.name" fit="contain" :z-index="9999" preview-teleported :preview-src-list="[deal?.image || '']" />
        </div>
        <!--        <div class="thumbnail-list">-->
        <!--          <div v-for="n in 4" :key="n" class="thumbnail">-->
        <!--            <el-image-->
        <!--              :src="deal?.image"-->
        <!--              :alt="deal?.name"-->
        <!--              fit="contain"-->
        <!--            />-->
        <!--          </div>-->
        <!--        </div>-->
      </div>

      <!-- 中间商品信息区域 -->
      <div class="product-info">
        <h1 class="title">{{ deal?.name }}</h1>
        <!--        <div class="brand">品牌：<a href="#">{{ deal?.brand }}</a></div>-->

        <!--        <div class="rating-section">-->
        <!--          <div class="stars">-->
        <!--            <el-rate-->
        <!--              :model-value="deal?.rating || 0"-->
        <!--              disabled-->
        <!--              text-color="#ff9900"-->
        <!--              show-score-->
        <!--              score-template="{value}"-->
        <!--            />-->
        <!--          </div>-->
        <!--          <a href="#reviews" class="reviews" @click.prevent="switchToReviews">-->
        <!--            {{ deal?.reviews?.toLocaleString() }} 条评价-->
        <!--          </a>-->
        <!--        </div>-->

        <div class="divider"></div>

        <div class="price-section">
          <div class="deal-badge">
            <span class="deal-tag">{{ $t('秒杀') }}</span>
            <span class="prime-tag">{{ $t('Prime专享') }}</span>
          </div>
          <div class="price-info">
            <div class="current-price">
              <span class="label">{{ $t('秒杀价') }}</span>
              <span class="currency">{{ langStore.languageSymbol }}</span>
              <span class="amount">{{ deal?.price*langStore.languageRate }}</span>
            </div>
            <div class="original-price">
              <span class="label">{{ $t('原价') }}：</span>
              <span class="strikethrough">{{ langStore.languageSymbol }}{{ deal?.price*langStore.languageRate }}</span>
            </div>
            <!--            <div class="save-info">-->
            <!--              <span class="save-amount">-->
            <!--                立省 ¥{{ ((deal?.originalPrice || 0) - (deal?.seckillPrice || 0))?.toLocaleString() }}-->
            <!--              </span>-->
            <!--              <span class="save-percentage">-->
            <!--                ({{ Math.round((1 - (deal?.seckillPrice || 0)/(deal?.originalPrice || 1)) * 100) }}% OFF)-->
            <!--              </span>-->
            <!--            </div>-->
          </div>
        </div>

        <!-- 秒杀倒计时 -->
        <div class="seckill-timer">
          <div class="timer-label" v-if="targetDataShou">{{ $t('距结束还剩') }}</div>
          <div class="timer-label" v-else>{{ $t('距开始还剩') }}</div>
          <div class="timer-digits">
            <span class="digit">{{ hours }}</span>
            <span class="colon">:</span>
            <span class="digit">{{ minutes }}</span>
            <span class="colon">:</span>
            <span class="digit">{{ seconds }}</span>
          </div>
        </div>

        <!-- 秒杀进度条 -->
        <!--        <div class="progress-section">-->
        <!--          <el-progress-->
        <!--            :percentage="deal?.soldPercentage"-->
        <!--            :show-text="false"-->
        <!--            :stroke-width="8"-->
        <!--            color="#FF4E4E"-->
        <!--          />-->
        <!--          <div class="progress-info">-->
        <!--            <span class="sold">已售 {{ deal?.soldCount?.toLocaleString() }} 件</span>-->
        <!--            <span class="stock">仅剩 {{ deal?.stockCount?.toLocaleString() }} 件</span>-->
        <!--          </div>-->
        <!--        </div>-->
      </div>

      <!-- 右侧购买区域 -->
      <div class="buy-box">
        <div class="price-display">
          <span class="currency">{{ langStore.languageSymbol }}</span>
          <span class="amount">{{ deal?.price }}</span>
        </div>

        <!--        <div class="stock-status">-->
        <!--          <i class="el-icon-goods"></i>-->
        <!--          现货 - 仅剩{{ deal?.stockCount || 0 }}件-->
        <!--        </div>-->

        <div class="quantity-selector">
          <div class="label">{{ $t('数量') }}：</div>
          <el-input-number
            v-model="productNum"
            :min="1"
            :max="9999"
            size="large"
          />
        </div>
        <div class="quantity-selector" style="display: flex; justify-content: space-between;">
          <div class="label">{{ $t('折扣') }}</div>
          <div class="label">{{ userVipLevelRate * 100 }}%</div>
        </div>
        <div class="quantity-selector" style="display: flex; justify-content: space-between;">
          <div class="label">{{ $t('原价') }}</div>
          <div class="label">{{ langStore.languageSymbol }}{{ deal?.price * langStore.languageRate * productNum  }}</div>
        </div>
        <div class="quantity-selector" style="display: flex; justify-content: space-between;">
          <div class="label">{{ $t('支付金额') }}</div>
          <div class="label">{{ langStore.languageSymbol }}{{ deal?.price * langStore.languageRate * productNum * (1 - userVipLevelRate) }}</div>
        </div>
        <div class="action-buttons">
          <button class="cart-button" @click="goToCart">
            {{ $t('加入购物车') }}
          </button>
          <button class="buy-button" @click="goToCheckout">
            {{ $t('立即购买') }}
          </button>
        </div>

        <!-- <div class="secure-transaction">
          <i class="el-icon-lock"></i>
          安全交易
        </div> -->
      </div>
    </div>

    <!-- 商品详情区域 -->
    <div class="product-details">
      <el-tabs v-model="activeTab">
        <el-tab-pane :label="$t('优惠券详情')" name="detail">
          <div class="detail-content">
            <h2>{{ $t('优惠券描述') }}</h2>
            <div v-if="deal?.detail" class="specs" v-html="deal.detail"></div>
          </div>
        </el-tab-pane>
        <!--        <el-tab-pane label="用户评价" name="reviews">-->
        <!--          <div class="reviews-section">-->
        <!--            &lt;!&ndash; 评价统计 &ndash;&gt;-->
        <!--            <div class="rating-summary">-->
        <!--              <div class="overall-rating">-->
        <!--                <span class="big-rating">{{ deal?.rating }}</span>-->
        <!--                <div class="stars">-->
        <!--                  <i class="fas fa-star" v-for="n in Math.floor(deal?.rating || 0)" :key="n"></i>-->
        <!--                  <i class="fas fa-star-half-alt" v-if="(deal?.rating || 0) % 1 >= 0.5"></i>-->
        <!--                </div>-->
        <!--                <span class="total-reviews">共 {{ deal?.reviews }} 条评价</span>-->
        <!--              </div>-->
        <!--            </div>-->

        <!--            &lt;!&ndash; 评论列表 &ndash;&gt;-->
        <!--            <div class="review-list">-->
        <!--              <div v-for="review in reviewList" :key="review.id" class="review-item">-->
        <!--                <div class="review-header">-->
        <!--                  <div class="user-info">-->
        <!--                    <img :src="review.avatar" alt="用户头像" class="avatar">-->
        <!--                    <span class="username">{{ review.username }}</span>-->
        <!--                  </div>-->
        <!--                  <div class="stars">-->
        <!--                    <i class="fas fa-star" v-for="n in review.rating" :key="n"></i>-->
        <!--                  </div>-->
        <!--                </div>-->
        <!--                <div class="review-content">-->
        <!--                  <div class="review-text">{{ review.content }}</div>-->
        <!--                  <div class="review-date">{{ review.date }}</div>-->
        <!--                </div>-->
        <!--              </div>-->
        <!--            </div>-->
        <!--          </div>-->
        <!--        </el-tab-pane>-->
      </el-tabs>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ApiAddCart, ApiBuyNow, ApiCommodityDetail, seckillget } from "@/api/commodity.js";
import {ElLoading, ElMessage, ElMessageBox} from "element-plus";
import useCartStore from "@/store/modules/cart.js";
import {useI18n} from "vue-i18n";
const { t } = useI18n();
import useLangStore from '@/store/modules/lang'
const langStore = useLangStore()
const cartStore = useCartStore()

const route = useRoute()
const router = useRouter()
const deal = ref(null)
const productNum = ref(1)
const timer = ref(null)
const endTime = ref(new Date().getTime() + 3600000) // 1小时后结束
const beginTime = ref('') // 1小时后结束

import useUserStore from '@/store/modules/user'

const userStore = useUserStore();

//折扣率
const userVipLevelRate = ref('0');
const userVipLevel = ref('0');
const buyLock = ref('0');

//获取个人信息
const getInfouser = async () => {
  const getInfouserStore = await userStore.getInfo();
  userVipLevelRate.value = getInfouserStore.data?.member?.userVipLevelRate || 0;
  userVipLevel.value = getInfouserStore.data?.member?.userVipLevel || 0;
  buyLock.value = getInfouserStore.data?.member?.buyLock || 0;
}
//获取倒计时开始和结束时间
const timeRemaining = ref(0); // 剩余时间（以秒为单位）
const intervalId = ref(null); // Interval 定时器 ID
const days = ref(0);
const hours = ref(0);
const minutes = ref(0);
const seconds = ref(0);
const getseckillget = async () => {


}
const targetDataShou = ref(false)
const calculateTimeRemaining = () => {
  let Countdown //倒计时结束时间
  const now = new Date().getTime(); // 当前时间戳
    // 指定的时间
  const targetDate = new Date(beginTime.value);

  // 当前时间
  const currentDate = new Date();

  // 判断是否大于当前时间
  if (targetDate > currentDate) {


    targetDataShou.value = false;
    Countdown = beginTime .value;
  } else {

    targetDataShou.value = true;
    Countdown = endTime.value;
    // console.log('2025-02-06 00:00:00 不大于当前时间');
  }

  const end = new Date(Countdown).getTime(); // 结束时间戳


  const remaining = Math.max((end - now) / 1000, 0); // 剩余时间（秒），确保为非负值
  timeRemaining.value = Math.floor(remaining);
  console.log(timeRemaining.value ,'timeRemaining.value ');

  if (timeRemaining.value > 0) {
    days.value = Math.floor(timeRemaining.value / (24 * 60 * 60));
    hours.value = Math.floor((timeRemaining.value % (24 * 60 * 60)) / (60 * 60));
    minutes.value = Math.floor((timeRemaining.value % (60 * 60)) / 60);
    seconds.value = Math.floor(timeRemaining.value % 60);
    console.log(hours,'hours');
    console.log(minutes,'minutes');
    console.log(seconds,'seconds');

  } else {
    // 倒计时结束
    clearInterval(intervalId.value);
  }
};
// 开始倒计时
const startCountdown = () => {
  calculateTimeRemaining(); // 立即计算一次
  intervalId.value = setInterval(calculateTimeRemaining, 1000); // 每秒更新一次
};




// 模拟加载秒杀商品详情数据
const loadDealDetail = async () => {
  const loading = ElLoading.service()
  try {
    const { data } = await ApiCommodityDetail({ productId: route.params.id })
    deal.value = data
    const detail = deal.value.detail ? JSON.parse(deal.value.detail) : {}
    deal.value.detail = detail?.des || ''

  endTime.value = data.endTime
  beginTime.value = data.beginTime
  // 计算剩余时间
  startCountdown();
  } catch (err) {
    console.error('Failed to load product detail:', err)
  } finally {
    loading.close()
  }
}

// 更新倒计时
const updateTimer = () => {
  timer.value = window.setInterval(() => {
    if (endTime.value <= new Date().getTime()) {
      clearInterval(timer.value)
    }
  }, 1000)
}

// 添加评论数据
const reviewList = [
  {
    id: 1,
    username: '张**',
    avatar: '/images/avatars/user1.jpg',
    rating: 5,
    content: '非常满意的一次购物体验！MacBook Pro的性能令人惊叹，M3 Pro芯片处理各种任务都很流畅。显示屏的素质也相当出色，色彩准确，亮度充足。',
    date: '2024-01-20'
  },
]

// 添加当前激活的标签页
const activeTab = ref('detail')

// 切换到评论标签页
const switchToReviews = () => {
  activeTab.value = 'reviews'
  // 平滑滚动到评论区域
  document.querySelector('.product-details')?.scrollIntoView({ behavior: 'smooth' })
}

// 跳转到购物车页面
const goToCart = async () => {
  const loading = ElLoading.service()
  try {
    await ApiAddCart({
      productId: deal.value.id,
      productNum: productNum.value
    })
    await cartStore.getCartList()
    loading.close()
    ElMessage.success(t('已添加到购物车'))
  } catch (error) {
    loading.close()
    console.error('Failed to add to cart:', error)
    ElMessage.error(t('添加购物车失败，请重试'))
  }
}

// 跳转到结算页面
const goToCheckout = () => {
  if(buyLock.value != '0'){
    return ElMessage.error(t('账户无法购买，请联系客服'));
  }
  ElMessageBox.prompt(t('请输入资金密码'), t('提示'), {
    confirmButtonText: t('确定'),
    cancelButtonText: t('取消'),
    showClose: false,
    closeOnClickModal: false,
    closeOnPressEscape: false,
    inputType: 'password',
    inputPattern: /^\d{6}$/,
    inputErrorMessage: t('资金密码为6位数字')
  }).then(({ value }) => {
    // console.log('支付密码是' + value)
    const loading = ElLoading.service()
    ApiBuyNow({
      productId: deal.value.id,
      num: productNum.value,
      assetPwd: value
    }).then(() => {
      ElMessage.success(t('购买成功'))
    }).finally(() => {
      loading.close()
    })
  }).catch(() => {
    console.log('取消输入')
  });
}

onMounted(() => {
  loadDealDetail()
  updateTimer()
  getInfouser()
  // getseckillget()
})

onUnmounted(() => {
  if (timer.value) {
    clearInterval(timer.value)// 清理定时器
  }
  if (intervalId.value) {
    clearInterval(intervalId.value); // 清理定时器
  }
})
</script>

<style lang="scss" scoped>
@use './style/detail.scss';
</style>
